<?php
defined( '_JEXEC' ) or die( 'Restricted access' );
JLoader::register('menuHelper',JPATH_COMPONENT.DS.'helpers'.DS.'menu.php');
JLoader::register('linioModellinio',JPATH_COMPONENT.DS.'models'.DS.'linio.php');

/**
* linioimport model Class for linio Component
* 
* @package    joomla.administrator.components.linio.models
* @subpackage components
* @author MAVLSoft - joomla! Component Creator 1.0
* @version 1.0
* @link http://www.mavlsoft.com/joomlacreator
* @license GNU General Public License version 3 or later; see http://www.gnu.org/copyleft/gpl.html
*/
class linioModellinioimport extends linioModellinio
{	
	
	/**
	 * Constructor that retrieves the ID from the request
	 *
	 * @access    public
	 * @return    void
	 */
	function __construct()
	{
		parent::__construct();	
	}
	
	/**
	 *
	 * Metodo para descargar el archivo CSV de Linio
	 * @param $url.- URL desde donde se descargara
	 * @param $file.- ruta del archivo.
	 */
	function downloadCsvFile($url,$path){
		set_time_limit(0); // unlimited max execution time
	
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_HEADER, false);
		curl_setopt($ch, CURLOPT_NOBODY, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
	
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
	
		//descargar el archivo
		$file = fopen($path, "w+");
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_FILE, $file);
		$retval = curl_exec($ch);
	
		fclose($file);
		curl_close($ch);
	
		return $retval;
	}
	
	/**
	 *
	 * Metodo para importar el archivo CVS de linio.
	 * @param $csvfile
	 */
	function importCvsFile($csvfile,$preserve=false){
	
		if(!file_exists($csvfile)) {
			return sprintf(JText::_('FILE_NOT_FOUND'),$csvfile); //File not found. Make sure you specified the correct path.
		}
	
		$this->log('[importCvsFile] Drop table liniocsv...');
		//drop table.
		$this->_db->setQuery("DELETE FROM ".$this->LINIO_CSV."");
		$this->_db->query();
	
		$fieldseparator = ";";
		$lineseparator = "\n";
		$enclosed = '"';
	
		$loadQuery = "LOAD DATA LOCAL INFILE ".$this->_db->quote($csvfile).
		" INTO TABLE ".$this->LINIO_CSV." ".
		" FIELDS TERMINATED BY ".$this->_db->quote($fieldseparator).
		" OPTIONALLY ENCLOSED BY ".$this->_db->quote($enclosed).
		" LINES TERMINATED BY ".$this->_db->quote($lineseparator).
		" IGNORE 1 LINES";
	
		$this->log('[importCvsFile] Query='.$loadQuery);
		$this->_db->setQuery($loadQuery);
		$this->_db->query();
		$affectedRows = $this->_db->getAffectedRows();
	
		// borrar archivo.
		if(!$preserve){
			unlink($csvfile);
		}
	
		//crear menu
		$this->log('[importCvsFile] crear menu');
		$this->createMenu();
		$this->mensaje[] = sprintf(JText::_('RECORDS_LOADED'),$affectedRows);
		$this->populateBrands();	
	}
	
	/**
	 *
	 * Metodo para crear la estructura del menu.
	 */
	function createMenu(){
		$categorySeparator = "/";
		$consecutivo = 0;
		$consecutivoHijo = 0;
		$i = 0;
		$itotal = 0;
	
		$this->log('[createMenu] Delete Menu...');
		$this->_db->setQuery("DELETE FROM ".$this->LINIO_MENU);
		$this->_db->query();
		$this->mensaje[] = sprintf(JText::_('RECORDS_DELETED'),$this->_db->getAffectedRows());
		
	
		// crear nodo raiz
		$root = new menuHelper($categorySeparator);
	
		$root->description = "menu";
		$root->id = 0;
		$root->parentid = 0;
		$this->log("[createMenu] root=".print_r($root,true));
	
		// buscar los elementos para el menu
		$select = "SELECT DISTINCT category FROM ".$this->LINIO_CSV." WHERE category IS NOT NULL ORDER BY category";
		$this->_db->setQuery($select);
		$column= $this->_db->loadResultArray();  //Array ( [0] => John Smith [1] => Magda Hellman [2] => Yvonne de Gaulle )
		$this->log("[createMenu] column=".print_r($column,true));
	
		// procesamos los resultados
		foreach ($column as $category) {
			if($category == null) {
				continue;
			}
			$this->log('\t[createMenu] Category = '.print_r($category,true));
			$itotal ++;
			$valores = explode($categorySeparator,$category);
			$this->log('		[createMenu] valores = '.print_r($valores,true));
			$padre = $root->getItem(trim($valores[0]));
	
			if ($padre == null) {
				$padre = new menuHelper($categorySeparator);
				$padre->id = ++$consecutivo;
				$padre->description = trim($valores[0]);
				$root->addItem($padre);
				$this->log('\t\t\t[createMenu] padre = '.print_r($padre,true));
				$this->insertMenu($padre->toSQLInsert());
				$consecutivoHijo = ($padre->id * 1000);
			} else {
	
			}
			for ($i = 1; $i < count($valores); $i++) {
				$description = trim($valores[$i]);
				$hijo = $padre->getItem($description);
				if ($hijo == null) {
					$hijo = new menuHelper($categorySeparator);
					$hijo->id = ++$consecutivoHijo;
					$hijo->description = $description;
					$padre->addItem($hijo);
					$this->insertMenu($hijo->toSQLInsert());
				}
				$padre = $hijo;
			}
		}
	
		$this->mensaje[] = sprintf(JText::_('ITEMS_LOADED'),$itotal);
	
	}
	
	/**
	 *
	 * agregar un item al menu
	 * @param string $query
	 */
	private function insertMenu($query){
		$this->log('[createMenu] $query = '.$query);
		$this->_db->setQuery($query);
		return $this->_db->query();
	}
	
	/**
	 *
	 * Optimizar tabla despues de cargar registros o borrarlos.
	 * @param $table
	 */
	function optimizeTable($table){
		// optimizar tabla.
		$this->_db->setQuery("OPTIMIZE TABLE ".$this->_db->nameQuote($table));
		$result = $this->_db->loadObject();
		return "[".$result->Table."]".$result->Op.$result->Msg_type."=".$result->Msg_text;
	}
	
	/**
	 * 
	 * Crear el catalogo de marcas
	 */
	function populateBrands(){
		$this->log('[populateBrands] Delete Brands...');
		$this->_db->setQuery("DELETE FROM ".$this->LINIO_BRANDS);
		$this->_db->query();
		$this->mensaje[] = sprintf(JText::_('RECORDS_DELETED'),$this->_db->getAffectedRows());
		
		$this->_db->setQuery("ALTER TABLE ".$this->LINIO_BRANDS." AUTO_INCREMENT = 1;");
		$this->_db->query();
		$affectedRows = $this->_db->getAffectedRows();

		$query = "INSERT INTO ".$this->LINIO_BRANDS." (`brand`,`total`) ".
				 "SELECT `brand`,COUNT(`brand`) AS `total` ".
				 "FROM ".$this->LINIO_CSV." ".
				 "WHERE `brand` IS NOT NULL ".
				 "GROUP BY `brand` ".
		         "ORDER BY `brand`";
		$this->_db->setQuery($query);
		$this->_db->query();
		$affectedRows = $this->_db->getAffectedRows();
		$this->mensaje[] = sprintf(JText::_('ITEMS_LOADED'),$affectedRows)." [Brands]";
		return $affectedRows;
	}

	/**
	 *
	 * Escribir un archivo LOG
	 * @param unknown_type $mensaje
	 */
	private function log($mensaje){
		//		$fp = fopen('C:\\linio.log', 'a');
		//		fwrite($fp, date("Y-m-d H:i:s").'[linioimport.php]'.$mensaje.PHP_EOL);
		//		fclose($fp);
	}
}
?>